package com.sdy.hospitalguard.biz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.common.model.BizException;
import com.sdy.common.model.FileObj;
import com.sdy.common.utils.Assert;
import com.sdy.hospitalguard.biz.constants.RedisConstants;
import com.sdy.hospitalguard.biz.dto.QrcodeDataDTO;
import com.sdy.hospitalguard.biz.mapper.QrcodeMapper;
import com.sdy.hospitalguard.biz.model.HospitalUser;
import com.sdy.hospitalguard.biz.model.Qrcode;
import com.sdy.hospitalguard.biz.service.ApplyPostService;
import com.sdy.hospitalguard.biz.service.HospitalUserService;
import com.sdy.hospitalguard.biz.service.QrcodeService;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 二维码表 服务实现类
 * </p>
 *
 * @author zzq
 * @since 2020-05-08
 */
@Slf4j
@Service
public class QrcodeServiceImpl extends BaseServiceImpl<Qrcode> implements QrcodeService {
    @Autowired
    private QrcodeMapper qrcodeMapper;
    @Autowired
    private HospitalUserService hospitalUserService;
    @Autowired
    private ApplyPostService applyPostService;
    @Autowired
    private RedisService redisService;

    @Override
    public QrcodeDataDTO getQrcodeData(Integer userId) throws BizException {
        HospitalUser byId = hospitalUserService.getById(userId);
        Assert.isNull(byId, "用户数据不完整!");
        // 此人目前的身份(0-无直接关系 1-患者 2-陪护 3-探视人员 4-陪护+探视)
        Integer identity = applyPostService.checkIdentity(userId);
        Qrcode one = getOne(Wrappers.<Qrcode>lambdaQuery().eq(Qrcode::getUserId, userId));
        QrcodeDataDTO qrcodeDataDTO = new QrcodeDataDTO();
        if (one != null) {
            qrcodeDataDTO.setName(byId.getName()).setQrAddress(one.getQrcodePath());
        } else {
            qrcodeDataDTO.setName(byId.getName());
        }
        // 返回图片数据
        if (StringUtils.isNotBlank(byId.getHeadPortrait())) {
            FileObj fileObj = redisService.get(RedisConstants.FILE_UPLOAD_UUID + byId.getHeadPortrait(), FileObj.class);
            qrcodeDataDTO.setFileObj(fileObj).setUuid(byId.getHeadPortrait()).setHeadPortrait(fileObj.getPath());
        }
        return qrcodeDataDTO.setIdentity(identity);
    }
}
